package JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 不同的线程处理不同的业务
public class TestCondition {
    public static void main(String[] args) throws InterruptedException {
        Data2 data2 = new Data2();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data2.increase();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data2.decrease();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data2.increase();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data2.decrease();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}

// 资源类
// Lock类模拟生产者消费者问题：等待、业务、通知三个流程
class Data2 {
    private int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
//    Condition condition2 = lock.newCondition();
    public void increase() throws InterruptedException {

        lock.lock();
        // 用while而不用if判断是防止虚假唤醒问题
        while (number != 0) {
            // 当 number != 0线程进入等待状态
            condition.await();
        }
        // 能进到这里说明number不等于0,number++后等于0
        number++;

        // 唤醒全部线程,告诉其他线程我加一了
        condition.signal();
        System.out.println(Thread.currentThread().getName() + " -> " + number);
        lock.unlock();

    }

    public void decrease() throws InterruptedException {

        lock.lock();
        // 用while而不用if判断是防止虚假唤醒问题
        while (number == 0) {
            // 当 number == 0线程进入等待状态
            condition.await();
        }
        // 能进到这里说明number等于0,number--后不等于0
        number--;

        // 唤醒全部线程,告诉其他线程我减一了
        condition.signal();
        System.out.println(Thread.currentThread().getName() + " -> " + number);
        lock.unlock();
    }
}
